export type FetchConfigProps = Omit<RequestInit, "body" | "params"> & {
  data?: Record<string, unknown>;
  params?: Record<string, unknown>;
};

export async function fetchData(url: string, options?: FetchConfigProps) {
  // 处理查询参数
  const parsedUrl = new URL(process.env.NEXT_PUBLIC_API_BASE_URL + url);
  console.log(parsedUrl.toString());
  if (options?.params) {
    Object.entries(options.params).forEach(([key, value]) => {
      if (value !== undefined) {
        parsedUrl.searchParams.append(key, String(value));
      }
    });
  }

  // 处理请求体
  const body = options?.data ? JSON.stringify(options.data) : undefined;
  try {
    const res = await fetch(parsedUrl.toString(), {
      ...options,
      body,
      headers: {
        "Content-Type": "application/json",
        ...options?.headers,
      },
    });
    const data = await res.json();
    return data;
  } catch (error) {
    return error
  }
}
